// pages/goodsDetail/goodsDetail.js
const WxParse = require('../../../wxParse/wxParse.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isCollection: false,
		goodsId: 0,
		detail: null,
		defaultSKU: null,
		chooseSKU: null,
		chooseSKUing: {
			length: 0
		},
		chooseSKUingTitles: '',
		cart_total_num: 0,
		specData: null,
		specValues: null,
		chooseSpecType: null,
		buyGoodsNum: 1
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.data.goodsId = options.id;
		this.onPullDownRefresh();
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		this.loadDetail().finally(() => {
			wx.stopPullDownRefresh();
		});
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		const detail = this.data.detail,
			title = detail ? detail.goods_name : '',
			image = detail && detail.image.length ? detail.image[0].file_path : null;
		return {
			title: title,
			imageUrl: image,
			path: this.route + `?id=${this.data.goodsId}`
		}
	},

	// 加载商品详情
	loadDetail: function() {
		return wx.http.get('api/goods/detail', {
			goods_id: this.data.goodsId
		}).then((res) => {
			const detail = res.data.data.detail;

			// 处理sku
			const defaultSKU = detail.sku[0];
			const defaultSKU2 = JSON.parse(JSON.stringify(defaultSKU));
			defaultSKU2.spec_sku_id = '';
			detail.sku = ((sku) => {
				const result = {};
				sku.forEach(it => result[it.spec_sku_id] = it);
				return result;
			})(detail.sku);

			// 处理多规格
			const specData = res.data.data.specData;
			if (specData && specData.spec_attr) {
				specData.spec_attr.forEach(it => {
					it.spec_items = it.spec_items.map(it => {
						return {
							text: it.spec_value,
							value: it.item_id,
						};
					});
				})
			}

			const cart_total_num = res.data.data.cart_total_num;

			this.setData({
				detail: detail,
				defaultSKU: defaultSKU,
				chooseSKU: defaultSKU2,
				cart_total_num: cart_total_num,
				specData: specData,
			}, () => {
				WxParse.wxParse('detailContent', 'html', detail.content, this);
			});
			return detail;
		}, (err) => {
			console.warn("api/goods/detail", err)
		});
	},

	// 选择商品规格
	onSpecChange: function(e) {
		// console.log(e);
		const index = e.currentTarget.dataset.index,
			value = e.detail;

		const chooseSkuing = this.data.chooseSKUing;
		chooseSkuing[index] = value;
		chooseSkuing.length = Object.keys(chooseSkuing).length - 1;

		const specValueKey = Array.from(chooseSkuing).join("_");
		const chooseSKU = this.data.detail.sku[specValueKey];
		const titles = Object.keys(chooseSkuing).map(it => {
			if (isNaN(it)) return undefined;

			const value = chooseSkuing[it];
			const item = this.data.specData.spec_attr[it].spec_items.find(it2 => {
				return it2.value == value;
			});

			return item ? item.text : undefined;
		}).filter(it => it);

		const data = {
			chooseSKUing: chooseSkuing,
			chooseSKUingTitles: titles.join(",")
		};
		if (chooseSKU) {
			data['chooseSKU'] = chooseSKU;
		}

		this.setData(data);
	},

	// 显示规格信息
	showChooseSpecTap: function(e) {
		const dataset = e.currentTarget.dataset,
			type = dataset.type;

		if (Object.keys(this.data.detail.sku).length === 1) {
			const chooseSKU = this.data.defaultSKU;
			this.groupSetData(() => {
				this.data.chooseSKU = chooseSKU;
				this.setData({
					chooseSKU: chooseSKU,
					chooseSpecType: null
				});
				if (type === 'cart') {
					this.addCart();
				} else if (type === 'buy') {
					this.buy();
				}
			});
		} else {
			const sku = this.data.chooseSKU;
			this.groupSetData(() => {
				const specValues = sku ? sku.spec_sku_id.split('_') : null;
				this.setData({
					specValues: specValues,
					chooseSpecType: type,
				});
			});
		}
	},

	// 规格选择
	onChooseSpecSubmit: function(e) {
		const values = e.detail.value;
		const result = [];
		for (const key in values) {
			const value = values[key];
			if (value === null) return;
			result.push(value);
		}

		const key = result.join("_");
		const chooseSKU = this.data.detail.sku[key];
		if (!chooseSKU) {
			wx.showToast({
				title: '请先选择商品规格！',
				icon: 'none',
			})
			return;
		}

		this.groupSetData(() => {
			this.data.chooseSKU = chooseSKU;
			const specType = this.data.chooseSpecType;
			this.setData({
				chooseSKU: chooseSKU,
				chooseSpecType: null
			});
			if (specType === 'cart') {
				this.addCart();
			} else if (specType === 'buy') {
				this.buy();
			}
		});
	},

	// 更改购买数量
	modifyGoodsNumTap: function(e) {
		const dataset = e.currentTarget.dataset,
			type = dataset.type;

		let totalNum = this.data.buyGoodsNum;

		// 减少
		if (type === '0') {
			totalNum = totalNum > 1 ? totalNum - 1 : 1;
		} else { // 增加
			totalNum++;
		}

		this.setData({
			buyGoodsNum: totalNum
		});

	},

	// 收藏
	collectionTap: function() {
		return wx.http.post('api/goods/collect', {
			goods_id: this.data.goodsId,
		}).then((res) => {
			const isCollect = !this.data.detail.isCollect;
			this.setData({
				'detail.isCollect': isCollect
			});
			return res.data.data;
		}, (err) => {
			console.warn("api/goods/collect", err)
		});
	},

	// 加入购物车
	addCart: function() {
		const num = this.data.cart_total_num + 1;
		return wx.http.post('api/cart/add', {
			goods_id: this.data.goodsId,
			goods_sku_id: this.data.chooseSKU.goods_sku_id,
			goods_num: this.data.buyGoodsNum,
		}).then((res) => {
			wx.showToast({
				title: '已加入购物车',
				icon: 'success',
			});
			this.setData({
				cart_total_num: num
			});
			return res.data.data;
		}, (err) => {
			console.warn("api/goods/collect", err)
		});
	},

	// 立即购买
	buy: function() {
		const chooseSKU = this.data.chooseSKU;
		const url = `/pages/mall/place-order/place-order?goods_id=${this.data.goodsId}&goods_sku_id=${chooseSKU.goods_sku_id}&goods_num=${this.data.buyGoodsNum}`;
		wx.navigateTo({
			url: url,
		});
	}
});
